<?php

namespace App\Http\Controllers;

use App\Http\Requests\OrderController\OrderConfirmReceiptRequest;
use App\Http\Requests\OrderController\OrderPayGoodRequest;
use App\Http\Resources\OrderResource;
use App\Models\Account;
use App\Models\ConsumeAccount;
use App\Models\ConsumeAccountLog;
use App\Models\Good;
use App\Models\Order;
use App\Models\ShopAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        $status = $request->get('status') ? $request->get('status') : 1;
        $page = $request->get('page') ? $request->get('page') : 1;

        $wheres[] = ['user_id', '=', $user->id];
        if ($status == 1) {
            $status = [0, 1];
        }else if ($status == 2) {
            $status = [2,3];
        }

        $order = Order::where($wheres)->whereIn('status', $status)->orderBy('id', 'desc')->paginate(20, $columns = ['order_number', 'good_id', 'number', 'price', 'status'], $pageName = 'page', $page);

        foreach ($order as $value) {
            $value->good = $value->good()->select('id', 'small_image', 'u_unit_price', 'name')->first();
        }

        return OrderResource::collection($order);
    }

    public function payGood(OrderPayGoodRequest $request)
    {
        $goodId = $request->input('good_id');
        $shopAddressId = $request->input('shop_address_id');
        $number = $request->input('number');
        $payPassword = $request->input('pay_password');

        $user = auth()->user();

        if (! Hash::check($payPassword, $user->pay_password)) {
            return $this->error(500, '交易密码错误');
        }

//        $consumeAccount = ConsumeAccount::where('user_id', $user->id)->where('coin_id', ConsumeAccount::COIN_ID[1])->first();
        $consumeAccount = Account::where('user_id', $user->id)->where('coin_id', ConsumeAccount::COIN_ID[1])->first();
        if (!$consumeAccount) {
            return $this->error(500, '帐户不存在');
        }

        $shopAddress = ShopAddress::where('id', $shopAddressId)->where('user_id', $user->id)->first();
        if (!$shopAddress) {
            return $this->error(500, '收货地址不存在');
        }

        $good = Good::where('id', $goodId)->where('status', 1)->first();
        if (! $good) {
            return $this->error(500, '商品不存在，或已下架');
        }

        $totalPrice = $number * $good->u_unit_price;
        if($consumeAccount->available < $totalPrice) {
            return $this->error(500, '余额不足');
        }

        DB::beginTransaction();
        try {

            $order = Order::create([
                'order_number' => Order::createOrderNumber(),
                'user_id' => $user->id,
                'good_id' => $goodId,
                'number' => $number,
                'price' => $totalPrice,
                'name' => $shopAddress->name,
                'phone' => $shopAddress->phone,
                'province' => $shopAddress->province,
                'city' => $shopAddress->city,
                'area' => $shopAddress->area,
                'detailed_address' => $shopAddress->detailed_address,
                'postal_code' => $shopAddress->postal_code
            ]);

            if (! isset($order->id)) {
                DB::rollBack();
                return $this->error(500, '订单创建失败');
            }

            $result = DB::table('account_logs')->insert(
                [
                    'user_id' => $user->id,
                    'coin_id' => ConsumeAccount::COIN_ID[1],
                    'type' => '购买商品',
                    'account_type' => 'available',
                    'action_id' => $order->id,
                    'before' => $consumeAccount->available,
                    'number' => $totalPrice,
                    'after' => $consumeAccount->available - $totalPrice,
                    'time' => now()
                ]
            );

            if (! $result) {
                DB::rollBack();
                return $this->error(500, '交易记录创建失败');
            }

            $consumeAccount->available = $consumeAccount->available - $totalPrice;
            $consumeAccountResult = $consumeAccount->save();
            if (! $consumeAccountResult) {
                DB::rollBack();
                return $this->error(500, '资产交易失败');
            }

            DB::commit();
            return $this->null();

        }catch (\Exception $exception) {
            Log::info($exception->getMessage());
            DB::rollBack();
            return $this->error(500, '购买失败');
        }
    }

    public function confirmReceipt(OrderConfirmReceiptRequest $request)
    {
        $user = auth()->user();
        $orderNumer = $request->input('order_number');
        $order = Order::where('order_number', $orderNumer)->where('user_id', $user->id)->where('status', 1)->first();
        if (! $order) {
            return $this->error(500, '订单不存在');
        }

        $order->status = 2;
        $result = $order->save();
        if (! $result) {
            return $this->error(500, '订单更新失败');
        }

        return $this->null();
    }

    public function show(OrderConfirmReceiptRequest $request)
    {
        $user = auth()->user();
        $orderNumer = $request->input('order_number');
        $order = Order::where('order_number', $orderNumer)->where('user_id', $user->id)->first();
        if (! $order) {
            return $this->error(500, '订单不存在');
        }

        $order->good = $order->good()->select('id', 'name', 'small_image', 'u_unit_price')->first();
        $order->good->small_image = config('app.image_url') . $order->good->small_image;

        return $this->array($order->toArray());
    }
}
